import subprocess  
import os  
import shutil
from datetime import datetime  
# 获取 ffpmeg 获取视频的格式
def get_video_format(video_file):  
    # 构造ffmpeg命令来检查视频信息  
    cmd = ['ffprobe', '-v', 'error', '-show_entries', 'format=format_name', '-of', 'default=noprint_wrappers=1:nokey=1', video_file]  
    # 运行命令并获取输出  
    try:  
        result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)  
        # 如果命令执行成功，则输出中应包含视频格式  
        if result.returncode == 0:  
            return result.stdout.decode('utf-8').strip()  
        else:  
            return None  
    except OSError as e:  
        return None  

# 获取 ffpmeg 的视频转换命令
def get_ffmpeg_convert_mp4_cmd(input_video_file, output_video_file):
    return ['ffmpeg', '-i', input_video_file, '-c:v', 'libx264', '-preset', 'slow', '-crf', '22', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', output_video_file]    

def convert_to_mp4(src_dir, output_dir):  
    for root, dirs, files in os.walk(src_dir):  
        for file in files:  
            file_path = os.path.join(root, file)  
            filename = os.path.splitext(os.path.basename(file_path))[0] + ".mp4"  
            # 构造ffmpeg命令来将视频转换为mp4格式  
            cmd = get_ffmpeg_convert_mp4_cmd(file_path, os.path.join(output_dir, filename))
            try:  
                print(f"start {file_path}") 
                process = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)  
                # 如果命令执行成功，则输出中应包含视频格式  
                if process.returncode == 0:  
                    print(f"SUCCESS[{datetime.now()}]: {file_path} convert to mp4")
                else:  
                    print(f"FAILED[{datetime.now()}]: {file_path} convert to mp4")
            except OSError as e:  
                    print(f"ERROR[{datetime.now()}]: {file_path} convert to mp4")

def transfer_non_mp4(directory, tmp_dir):
    if not os.path.exists(tmp_dir):
        os.mkdir(tmp_dir)

    for root, dirs, files in os.walk(directory):  
        for file in files:  
            file_path = os.path.join(root, file)  
            if os.path.isfile(file_path) and file_path.find(directory) == -1:
                format_name = get_video_format(file_path)  
                # 文件是视频，且不是mp4格式
                if format_name and format_name.find('mp4') == -1:  
                    print(f"transfer: {file_path}")
                    shutil.move(file_path, tmp_dir)

# 使用示例  
directory = 'E:\\tmp\\recycle\\video'  
tmp_dir = 'E:\\tmp\\recycle\\video\\tmp'

# 将 directory 目录（递归)下的 非 mp4 格式的文件，移动到 tmp_dir 目录
# 两个目录最好是同一块磁盘，避免移动的开销（同一块磁盘只是索引的修改）
transfer_non_mp4(directory, tmp_dir)
print("begin to convert to mp4")
# 将 tmp_dir 目录下的 mp4 格式的文件，转换到 D:\\tmp 目录
convert_to_mp4(tmp_dir, "D:\\tmp")
                